<script setup lang="ts">
import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/services/home'
import CustomNavbar from './components/CustomNavbar.vue'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'
import type { XtxGuessInstance } from '@/types/components'

//将获取到的数据保存到其中 , 类型为数组.准备一个变量用来接收数据
const bannerList = ref<BannerItem[]>([])
// 将封装好的请求函数在页面中调用
const getHomeBannerData = async () => {
  const res = await getHomeBannerAPI()
  // console.log(res)
  // 将获取到的数据保存到其中.然后存储起来.
  bannerList.value = res.result
}

// 获取前台分类数据
const categoryList = ref<CategoryItem[]>([])
const getHomeCategoryData = async () => {
  const res = await getHomeCategoryAPI()
  // console.log(res)
  categoryList.value = res.result
}

// 获取热门推荐数据
const hotList = ref<HotItem[]>([])
const getHomeHotData = async () => {
  const res = await getHomeHotAPI()
  // console.log(res)
  hotList.value = res.result
}

// 调用获取到的数据
// 页面加载时调用,这是回调函数
onLoad(() => {
  getHomeBannerData()
  getHomeCategoryData()
  getHomeHotData()
})

// 获取子组件的实例
const guessRef = ref<XtxGuessInstance>()
const onScrolltolower = () => {
  // console.log('触底')
  getHomeBannerData()
  getHomeCategoryData()
  getHomeHotData()
}

// 当前下拉刷新状态
const isRefresherTriggered = ref(false)
const onRefresherrefresh = async () => {
  // console.log('下拉刷新')
  // 下拉刷新状态
  isRefresherTriggered.value = true
  // 获取数据
  // 重置数据
  guessRef.value?.resetData()
  // 使用Promise.all() 方法来并行执行多个异步操作
  await Promise.all([
    getHomeBannerData(),
    getHomeCategoryData(),
    getHomeHotData(),
    guessRef.value?.getMore(),
  ])
  isRefresherTriggered.value = false
}
</script>

<template>
  <!-- 在父组件当中导入子组件 -->
  <!-- 父组件通过自定义属性向子组件传递数据 ,将定义好的数据传递给子组件-->
  <!-- 头部导航 -->
  <CustomNavbar />
  <scroll-view
    refresher-enabled
    @refresherrefresh="onRefresherrefresh"
    :refresher-triggered="isRefresherTriggered"
    @scrolltolower="onScrolltolower"
    class="scroll-view"
    scroll-y
  >
    <!-- 轮播图 -->
    <XtxSwiper :list="bannerList" />
    <!-- 分类面板 -->
    <CategoryPanel :list="categoryList" />
    <!-- 热门推荐 -->
    <HotPanel :list="hotList" />
    <!-- 猜你喜欢 -->
    <XtxGuess ref="guessRef" />
  </scroll-view>
</template>

<style lang="scss">
//
page {
  background-color: #f4f4f4;
  height: 100vh;
  display: flex;
  flex-direction: column;
}
.scroll-view {
  flex: 1;
}
</style>
